package com.bruce.timerTask;

import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;

import java.util.TimerTask;

/**
 * Created by Bruce on 2016/11/26.
 */
public class MyTimerTask {
    private static MyTimerTask task;
    private static Camera camera;
    private static Camera.Parameters parameters;
    private TimerTask taskOpen;
    private TimerTask taskClose;
    private CameraManager cameraManager;
    private String cameraId;
    private static boolean mode;


    private MyTimerTask() {
    }

    public static MyTimerTask getTask() {
        if (task == null) {
            task = new MyTimerTask();
        }
        return task;
    }

    public void setCameraManager(CameraManager cameraManager, String cameraId) {
        this.cameraId = cameraId;
        this.cameraManager = cameraManager;
        mode = false;
    }

    public void setCamera() {
        mode = true;
        camera = Camera.open();
        camera.startPreview();
        parameters = camera.getParameters();
    }

    public TimerTask getOpenTask() {
        taskOpen = new TimerTask() {
            @Override
            public void run() {
                try {
                    open();
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        };
        return taskOpen;
    }

    public TimerTask getCloseTask() {
        taskClose = new TimerTask() {
            @Override
            public void run() {
                try {
                    close();
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        };
        return taskClose;
    }

    public void free() throws CameraAccessException {
        if (camera != null) {
            camera.release();
        }
        if (!mode) {
            cameraManager.setTorchMode(cameraId, false);
        }
    }

    private void close() throws CameraAccessException {
        if (mode) {
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);//关灯
            camera.setParameters(parameters);
        } else {
            cameraManager.setTorchMode(cameraId, false);
        }
    }

    private void open() throws CameraAccessException {
        if (mode) {
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);//开灯
            camera.setParameters(parameters);
        } else {
            cameraManager.setTorchMode(cameraId, true);
        }
    }
}
